package com.ng.biz.controller;

import com.ng.common.model.response.R;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.opencsv.CSVReader;
import com.opencsv.exceptions.CsvValidationException;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

@Tag(name = "文件上传解析")
@RestController
@RequestMapping("/biz/file")
public class FileUploadController {

    @Operation(summary = "上传并解析文件")
    @Parameters({
        @Parameter(name = "file", description = "上传的文件", required = true)
    })
    @PostMapping("/upload")
    public R<List<List<String>>> uploadFile(@RequestParam("file") MultipartFile file) {
        String fileName = file.getOriginalFilename();
        if (fileName == null) {
            return R.failed("文件名不能为空");
        }

        try {
            if (fileName.endsWith(".xlsx") || fileName.endsWith(".xls")) {
                return R.ok(parseExcel(file));
            } else if (fileName.endsWith(".csv")) {
                return R.ok(parseCsv(file));
            } else {
                return R.failed("不支持的文件格式");
            }
        } catch (Exception e) {
            return R.failed("文件解析失败: " + e.getMessage());
        }
    }

    private List<List<String>> parseExcel(MultipartFile file) throws IOException {
        List<List<String>> data = new ArrayList<>();
        try (InputStream is = file.getInputStream();
             Workbook workbook = new XSSFWorkbook(is)) {
            Sheet sheet = workbook.getSheetAt(0);
            for (Row row : sheet) {
                List<String> rowData = new ArrayList<>();
                for (Cell cell : row) {
                    rowData.add(cell.toString());
                }
                data.add(rowData);
            }
        }
        return data;
    }

    private List<List<String>> parseCsv(MultipartFile file) throws IOException, CsvValidationException {
        List<List<String>> data = new ArrayList<>();
        try (Reader reader = new InputStreamReader(file.getInputStream());
             CSVReader csvReader = new CSVReader(reader)) {
            String[] nextLine;
            while ((nextLine = csvReader.readNext()) != null) {
                List<String> rowData = new ArrayList<>();
                for (String value : nextLine) {
                    rowData.add(value);
                }
                data.add(rowData);
            }
        }
        return data;
    }
} 